package com.gtmc.ecm.common.core.utils;

import com.csvreader.CsvWriter;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * @description: CSV操作工具类
 * @author: zhz
 * @create: 2021/12/22 10:59
 */
@Slf4j
public class CSVUtil {

    /**
     * 生成 CSV文件
     *
     * @param head     头部属性
     * @param dataList 对象集合
     * @param filePath 文件路径
     * @return
     */
    public static <T> Boolean createCSVFile(String[] head, Collection<T> dataList, String filePath) {
        Boolean bool = false;
        CsvWriter csvWriter = null;
        try {
            // 定义路径，分隔符，编码
            csvWriter = new CsvWriter(filePath, ',', Charset.forName("GBK"));
            // 写表头
            csvWriter.writeRecord(head);
            // 写内容
            //遍历集合
            Iterator<T> it = dataList.iterator();
            while (it.hasNext()) {
                T t = (T) it.next();
                //获取类属性
                Field[] fields = t.getClass().getDeclaredFields();
                String[] csvContent = new String[fields.length];
                for (short i = 0; i < fields.length; i++) {
                    Field field = fields[i];
                    String fieldName = field.getName();
                    String getMethodName = "get"
                            + fieldName.substring(0, 1).toUpperCase()
                            + fieldName.substring(1);
                    try {
                        Class tCls = t.getClass();
                        Method getMethod = tCls.getMethod(getMethodName, new Class[]{});
                        Object value = getMethod.invoke(t, new Object[]{});
                        if (value == null) {
                            continue;
                        }
                        //取值并赋给数组
                        String textvalue = value.toString();
                        csvContent[i] = textvalue;
                    } catch (Exception e) {
                        e.getStackTrace();
                    }
                }
                //迭代插入记录
                csvWriter.writeRecord(csvContent);
            }
            System.out.println("<--------CSV文件：" + filePath + " 写入成功-------->");
            bool = true;
        } catch (IOException e) {
            e.printStackTrace();
            bool = false;
        } finally {
            csvWriter.close();
        }
        return bool;
    }

    /**
     * 读取csv文件数据到对象集合中
     *
     * @param inputStream 文件输入流
     * @param charset     文件字符集
     * @param clazz       类
     * @param <T>         泛型
     * @return
     */
    public static <T> List<T> readCSVFile(InputStream inputStream, String charset, Class<T> clazz) {
        CsvToBean<T> csvToBean = null;
        try {
            InputStreamReader in = new InputStreamReader(inputStream, charset);
            HeaderColumnNameMappingStrategy<T> strategy = new HeaderColumnNameMappingStrategy<>();
            strategy.setType(clazz);
            csvToBean = new CsvToBeanBuilder<T>(in).withMappingStrategy(strategy).build();
        } catch (Exception e) {
            log.error("数据转化失败", e);
            return Collections.emptyList();
        }
        List list = csvToBean.parse();

        return list;
    }

    /**
     * @Author zhz
     * @Description 对临时生成的文件夹和文件夹下的文件进行删除
     * @param delpath
     * @return void
     */
    public static void deletefile(String delpath) {
        try {
            File file = new File(delpath);
            if (!file.isDirectory()) {
                file.delete();
            } else if (file.isDirectory()) {
                String[] fileList = file.list();
                for (int i = 0; i < fileList.length; i++) {
                    File delfile = new File(delpath + File.separator + fileList[i]);
                    if (!delfile.isDirectory()) {
                        delfile.delete();
                    } else if (delfile.isDirectory()) {
                        deletefile(delpath + File.separator + fileList[i]);
                    }
                }
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
